package com.jsh.erp.service.address;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.AccountHead;
import com.jsh.erp.datasource.entities.DepotHead;
import com.jsh.erp.datasource.entities.Address;
import com.jsh.erp.datasource.entities.AddressExample;
import com.jsh.erp.datasource.mappers.AccountHeadMapperEx;
import com.jsh.erp.datasource.mappers.DepotHeadMapperEx;
import com.jsh.erp.datasource.mappers.AddressMapper;
import com.jsh.erp.datasource.mappers.AddressMapperEx;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AddressService {
    private Logger logger = LoggerFactory.getLogger(AddressService.class);

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private AddressMapperEx addressMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private AccountHeadMapperEx accountHeadMapperEx;
    @Resource
    private DepotHeadMapperEx depotHeadMapperEx;
    @Resource
    private SystemConfigService systemConfigService;

    public Address getAddress(String id)throws Exception {
        Address result=null;
        try{
            result=addressMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<Address> getAddressListByIds(String ids)throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        List<Address> list = new ArrayList<>();
        try{
            AddressExample example = new AddressExample();
            example.createCriteria().andIdIn(idList);
            list = addressMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<Address> getAddress()throws Exception {
        AddressExample example = new AddressExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Address> list=null;
        try{
            list=addressMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<Address> select(String name, int offset, int rows)throws Exception {
        List<Address> list=null;
        try{
            list=addressMapperEx.selectByConditionAddress(name, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long countAddress(String name, String type)throws Exception {
        Long result=null;
        try{
            result=addressMapperEx.countsByAddress(name);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertAddress(JSONObject obj, HttpServletRequest request)throws Exception {
        Address address = JSONObject.parseObject(obj.toJSONString(), Address.class);
        address.setUploadFlag("0");
        int result=0;
        try{
            result=addressMapper.insertSelective(address);
            logService.insertLog("地址",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(address.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateAddress(JSONObject obj, HttpServletRequest request)throws Exception {
        Address address = JSONObject.parseObject(obj.toJSONString(), Address.class);
        address.setUploadFlag("0");
        int result=0;
        try{
            result=addressMapper.updateByPrimaryKeySelective(address);
            logService.insertLog("地址",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(address.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteAddress(String id, HttpServletRequest request)throws Exception {
        return batchDeleteAddressByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteAddress(String ids, HttpServletRequest request) throws Exception{
        return batchDeleteAddressByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteAddressByIds(String ids)throws Exception {
        int result =0;
        String [] idArray=ids.split(",");
        //记录日志
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Address> list = getAddressListByIds(ids);
        for(Address address: list){
            sb.append("[").append(address.getName()).append("]");
        }
        logService.insertLog("地址", sb.toString(),StringUtil.getRequest());
        //删除地址
        try{
            result=addressMapperEx.batchDeleteAddressByIds(idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public int checkIsNameExist(String id, String name) throws Exception{
        AddressExample example = new AddressExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Address> list =null;
        try{
            list=addressMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list==null?0:list.size();
    }

    public Map<String,String> getAddressMap() throws Exception {
        List<Address> addressList = getAddress();
        Map<String,String> addressMap = new HashMap<>();
        for(Address address : addressList){
            addressMap.put(address.getId(), address.getName());
        }
        return addressMap;
    }

    public String getAddressByMapAndIds(Map<String,String> addressMap, String addressIds)throws Exception {
        List<String> ids = StringUtil.strToStringList(addressIds);
        StringBuffer sb = new StringBuffer();
        for(String id: ids){
            sb.append(addressMap.get(id) + " ");
        }
        return sb.toString();
    }

    public List<Address> getAddressByType(String type)throws Exception {
        AddressExample example = new AddressExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("id asc");
        List<Address> list =null;
        try{
            list=addressMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
}
